package flc.ast.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Dialog;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.PathUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.zyyoona7.popup.EasyPopup;
import com.zyyoona7.popup.XGravity;
import com.zyyoona7.popup.YGravity;

import java.util.Random;

import VideoHandle.EpAudio;
import VideoHandle.EpEditor;
import VideoHandle.OnEditorListener;
import flc.ast.BaseAc;
import flc.ast.HomeActivity;
import flc.ast.R;
import flc.ast.databinding.ActivityAudioFormatBinding;
import flc.ast.utils.Content;
import flc.ast.view.BaseAvTrackView;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.media.audio.AudioPlayerImpl;
import stark.common.basic.media.audio.IAudioPlayer;
import stark.common.basic.utils.FileP2pUtil;
import stark.common.basic.utils.FileUtil;
import stark.common.basic.utils.RxUtil;

public class AudioFormatActivity extends BaseAc<ActivityAudioFormatBinding> implements IAudioPlayer.IListener {

    public static String audioPath;
    protected IAudioPlayer mAudioPlayer;
    private EasyPopup mCirclePop;
    private TextView tvMp3;
    private TextView tvWav;
    private TextView tvAac;
    private TextView tvFlac;
    private boolean isInitTrackViewDuration = false;
    private String suffixName = ".mp3";
    private String mAudioName;
    private Dialog myRenameDialog;
    private EditText editText;

    @Override
    protected int onCreate() {
        return R.layout.activity_audio_format;
    }

    @Override
    protected void initView() {
        mDataBinding.ivAudioFormatBack.setOnClickListener(v -> onBackPressed());

        mDataBinding.tvName.setOnClickListener(this);
        mAudioPlayer = new AudioPlayerImpl();
        mAudioPlayer.play(audioPath);
        mAudioPlayer.setListener(this);
        mDataBinding.ivAudioFormatSave.setOnClickListener(this);
        mDataBinding.ivPlay.setOnClickListener(this);
        mDataBinding.tvTargetFormat.setOnClickListener(this);
        mDataBinding.trackView.setTrackBgColor(Color.parseColor("#1D2022"));
        mDataBinding.trackView.setListener(new BaseAvTrackView.IListener() {
            @Override
            public void onStartTimeChanged(long startTime) {
                if (mAudioPlayer != null) {
                    mAudioPlayer.seekTo((int) startTime);
                    mAudioPlayer.resume();
                }
            }

            @Override
            public void onEndTimeChanged(long endTime) {
                if (mAudioPlayer != null) {
                    mAudioPlayer.seekTo((int) endTime);
                    mAudioPlayer.resume();
                }
            }

            @Override
            public void onStartEndTimeChanged(long startTime, long endTime) {
                if (mAudioPlayer != null) {
                    mAudioPlayer.seekTo((int) startTime);
                    mAudioPlayer.resume();
                }
            }
        });
        //重命名弹框
        renameDialog();
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivPlay://播放
                if (mAudioPlayer == null) {
                    return;
                }
                if (mAudioPlayer.isPlaying()) {
                    mAudioPlayer.pause();
                } else {
                    mAudioPlayer.resume();
                }
                break;
            case R.id.tvTargetFormat://格式选择
                if (mCirclePop == null) {
                    mCirclePop = EasyPopup.create().setContentView(this, R.layout.layout_format_style)
                            //是否允许点击PopupWindow之外的地方消失
                            //是否允许点击PopupWindow之外的地方消失
                            .setFocusAndOutsideEnable(true)
                            //允许背景变暗
                            .setBackgroundDimEnable(true)
                            //变暗的透明度(0-1)，0为完全透明
                            .setDimValue(0.4f).apply();
                } else {
                    mCirclePop.setFocusAndOutsideEnable(true)
                            //允许背景变暗
                            .setBackgroundDimEnable(true)
                            //变暗的透明度(0-1)，0为完全透明
                            .setDimValue(0.4f).apply();
                }
                tvMp3 = mCirclePop.findViewById(R.id.tvMp3);
                tvWav = mCirclePop.findViewById(R.id.tvWav);
                tvAac = mCirclePop.findViewById(R.id.tvAac);
                tvFlac = mCirclePop.findViewById(R.id.tvFlac);
                tvMp3.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mCirclePop.dismiss();
                        clearFormat();
                        tvMp3.setTextColor(Color.parseColor("#2F53FF"));
                        suffixName = ".mp3";
                        mDataBinding.tvTargetFormat.setText(getString(R.string.target_format_text1) + suffixName);
                    }
                });
                tvWav.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mCirclePop.dismiss();
                        clearFormat();
                        tvWav.setTextColor(Color.parseColor("#2F53FF"));
                        suffixName = ".wav";
                        mDataBinding.tvTargetFormat.setText(getString(R.string.target_format_text1) + suffixName);
                    }
                });
                tvAac.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mCirclePop.dismiss();
                        clearFormat();
                        tvAac.setTextColor(Color.parseColor("#2F53FF"));
                        suffixName = ".aac";
                        mDataBinding.tvTargetFormat.setText(getString(R.string.target_format_text1) + suffixName);
                    }
                });
                tvFlac.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mCirclePop.dismiss();
                        clearFormat();
                        tvFlac.setTextColor(Color.parseColor("#2F53FF"));
                        suffixName = ".flac";
                        mDataBinding.tvTargetFormat.setText(getString(R.string.target_format_text1) + suffixName);
                    }
                });
                mCirclePop.showAtAnchorView(mDataBinding.tvTargetFormat, YGravity.BELOW, XGravity.CENTER, 0, 0);
                break;
            case R.id.tvName://重命名
                myRenameDialog.show();
                break;
            //重命名
            case R.id.tvDialogRenameConfirm:
                String name = editText.getText().toString();
                if (TextUtils.isEmpty(name)) {
                    ToastUtils.showShort(getText(R.string.please_input_video_name));
                    return;
                }
                mAudioName = name;
                mDataBinding.tvName.setText(mAudioName + "." + FileUtils.getFileExtension(audioPath));
                myRenameDialog.dismiss();
                editText.setText("");
                break;
            case R.id.tvDialogRenameCancel:
                editText.setText("");
                myRenameDialog.dismiss();
                break;
            case R.id.ivAudioFormatSave://保存
                clickStartConvert();
                break;
        }
    }

    @Override
    protected void initData() {
        mAudioName = FileUtils.getFileNameNoExtension(audioPath);
        mDataBinding.tvName.setText(FileUtils.getFileName(audioPath));
        mDataBinding.tvOrig.setText(getString(R.string.origin_format_text) + FileUtils.getFileExtension(audioPath));
    }

    private void clickStartConvert() {
        showDialog(getString(R.string.saving));
        String clipPath = FileUtil.generateFilePath(Content.myTemp, "." + FileUtils.getFileExtension(audioPath));
        String path = PathUtils.getFilesPathExternalFirst() + Content.myTemp + "/" + mAudioName + suffixName;
        RxUtil.create(new RxUtil.Callback<Boolean>() {
            @Override
            public void doBackground(ObservableEmitter<Boolean> emitter) {
                EpAudio epAudio = new EpAudio(audioPath);
                float startTime = mDataBinding.trackView.getStartTime() / 1000f;
                float duration = mDataBinding.trackView.getEndTime() / 1000f - startTime;
                if (duration < 0) {
                    duration = 0;
                }
                epAudio.clip(startTime, duration);
                EpEditor.audioExec(epAudio, clipPath, new OnEditorListener() {
                    @Override
                    public void onSuccess() {
                        emitter.onNext(true);
                    }

                    @Override
                    public void onFailure() {
                        dismissDialog();
                        emitter.onNext(false);
                    }

                    @Override
                    public void onProgress(float progress) {

                    }
                });
            }

            @Override
            public void accept(Boolean result) {
                if (result) {
                    EpEditor.audioFormatConvert(clipPath, path, new OnEditorListener() {
                        @Override
                        public void onSuccess() {
                            dismissDialog();
                            ToastUtils.showShort(getString(R.string.save_success));
                            FileP2pUtil.copyPrivateAudioToPublic(mContext, path);
                            startActivity(HomeActivity.class);
                        }

                        @Override
                        public void onFailure() {
                            dismissDialog();
                            ToastUtils.showShort(R.string.format_failure);
                        }

                        @Override
                        public void onProgress(float progress) {

                        }
                    });
                } else {
                    dismissDialog();
                    ToastUtils.showShort(R.string.clips_failure);
                }
            }
        });

    }

    @Override
    public void onUpdatePlayTime(int curPlayTime, int duration) {
        if (!isInitTrackViewDuration) {
            isInitTrackViewDuration = true;
            mDataBinding.trackView.setDuration(duration);
        }
        mDataBinding.trackView.setPlayTime(curPlayTime);
    }

    @Override
    public void onPlayChange(boolean isPlaying) {
        if (isPlaying) {
            mDataBinding.ivPlay.setImageResource(R.drawable.abofzhong);
        } else {
            mDataBinding.ivPlay.setImageResource(R.drawable.azantinz);
        }
    }

    private void clearFormat() {
        tvMp3.setTextColor(Color.parseColor("#000000"));
        tvWav.setTextColor(Color.parseColor("#000000"));
        tvAac.setTextColor(Color.parseColor("#000000"));
        tvFlac.setTextColor(Color.parseColor("#000000"));
    }

    //重命名弹框
    private void renameDialog() {
        myRenameDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_rename, null);
        myRenameDialog.setContentView(inflate);
        myRenameDialog.setCancelable(true);
        Window dialogWindow = myRenameDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.CENTER);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 0.8);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        TextView cancel = inflate.findViewById(R.id.tvDialogRenameCancel);
        TextView comp = inflate.findViewById(R.id.tvDialogRenameConfirm);
        editText = inflate.findViewById(R.id.etDialogFormatRename);
        cancel.setOnClickListener(this);
        comp.setOnClickListener(this);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mAudioPlayer != null) {
            mAudioPlayer.resume();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mAudioPlayer != null) {
            mAudioPlayer.pause();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mAudioPlayer != null) {
            mAudioPlayer.stop();
        }
        FileUtils.deleteAllInDir(PathUtils.getFilesPathExternalFirst() + Content.myTemp);
    }

}